package com.yj.provider.validator;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.List;

@RestControllerAdvice
public class ValidatorException {


    @ExceptionHandler(Exception.class)
    public String handler(Exception e){
        if (e instanceof BindException){
            BindException ex = (BindException) e;
            List<ObjectError> allErrors =
                    ((BindException) e).getAllErrors();
            String defaultMessage = allErrors.get(0).getDefaultMessage();
            System.out.println(defaultMessage);
            return defaultMessage;
        }
        return "error";
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public String validationException(ConstraintViolationException e){
        System.out.println("11111111111111");
        Iterator it = e.getConstraintViolations().iterator();
        String error = "";
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        return "error";
    }

}
